<?php

namespace app\controller\api;

use app\validate\AmqpValidate;
use share\controller\ApiBaseController;
use think\Log;

class AmqpController extends ApiBaseController{

    public function initValidate(){
        $this->validate = new AmqpValidate();
    }

    public function callback_action(){
        if(!$this->check_callback_access()){
            return self::fail('no access to call this api',401);
        }
        $input = $this->check();
        $service = $input['service']; // 回调时  三方可能多个转义
        if(strpos($service,'\\\\')) {
            $service = stripcslashes($service);
        }
        $params = $input['params'];
        $serviceInfo = explode('@',$service);
        $class = $serviceInfo[0];
        $method = $serviceInfo[1];
        if(!method_exists($class,$method)){
            trace("mq.callback service ".$service." not exist!",Log::ERROR);
            return self::ok();
        }
        // 不限制执行时间
        @set_time_limit(0);
        $res = null;
        if(isset($params[0])){ //数组形式的参数
            $res = call_user_func_array([$class,$method],$params);
        }
        else{
            $res = call_user_func([$class,$method],$params);
        }
        return self::ok($res);
    }

    /**
     * 检查回调权限
     */
    protected function check_callback_access(){
        $ip = $this->request->ip();
        $ipPrefix = substr($ip,0,3);
        //如果是本地局域网的 
        if($ipPrefix === '127' || $ipPrefix === '192' || $ipPrefix === '172' || $ipPrefix === '10.'){
            return true;
        }
        $param = $this->request->param();
        $mqKey = config("MQ_AUTH_KEY");
        $mqSecret = config("MQ_AUTH_SECRET");
        if(isset($param[$mqKey]) && $param[$mqKey] === $mqSecret){
            return true;
        }
        return false;
    }
}